#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from urlparse import urlparse
from google.appengine.ext.webapp import template
register = template.create_template_register()

@register.filter(name = 'truncatehanzi')
def truncatehanzi(value, arg):     
    """     
    Truncates a string after a certain number of words including     
    alphanumeric and CJK characters.      
    Argument: Number of words to truncate after.     
    """     
    try:
        bits = []
        for x in arg.split(u':'):
            if len(x) == 0:
                bits.append(None)
            else:
                bits.append(int(x))
        if int(x) < len(value):
            return value[slice(*bits)] + '...'
        return value[slice(*bits)]

    except (ValueError, TypeError):
        return value # Fail silently.
    

@register.filter(name = 'gethostnamefromurl')
def gethostnamefromurl(value):     
    """     
    Truncates a string after a certain number of words including     
    alphanumeric and CJK characters.      
    Argument: Number of words to truncate after.     
    """     
    try:
        url = urlparse(value)
        return url.hostname

    except (ValueError, TypeError):
        return value # Fail silently.


@register.filter(name = 'texttohtml')
def texttohtml(value):
    try:
        value = value.replace("\r\n", "<br>")
        value = value.replace("\r", "<br>")
        value = value.replace("\n", "<br>")
        value = value.replace("\t", "&emsp;")
        return value

    except (ValueError, TypeError):
        return value # Fail silently.

